//
//  URLManager.m
//  ShenWeiRent
//
//  Created by iMac on 2019/3/1.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "URLManager.h"
#import "ANLoginController.h"
#import "ANNavigationController.h"

static NSString *POST = @"POST";
static NSString *GET = @"GET";

@interface URLManager ()


@end

@implementation URLManager

static URLManager *_manager;
+ (instancetype)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    });
    return _manager;
}

- (void)requestUrlStr:(NSString *)urlStr
               method:(NSString *)method
           parameters:(nullable id)parameters
              success:(void (^)(NSURLResponse * _Nonnull response, id _Nullable responseObj))success
              failure:(void (^)(NSURLResponse * _Nullable response, NSError * _Nonnull error))failure
{
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:
                                                 @"application/json",
                                                 @"text/html",
                                                 @"text/json",
                                                 @"text/javascript",
                                                 @"text/plain",
                                                 @"application/x-www-form-urlencoded",
                                                 @"multipart/form-data",
                                                 nil];
    self.responseSerializer = responseSerializer;
    NSString *url = [NSString stringWithFormat:@"%@%@", SERVERADDRS, urlStr];
//    NSMutableDictionary *para = parameters;
//    if (para) {
//        para = para.mutableCopy;
//    }
//    else {
//        para = @{}.mutableCopy;
//    }
    if ([UserUtils shared].session.length > 0) {
//        para[@"3rdsession"] = [UserUtils shared].session;
//        para[@"3rdsession"] = @"190410105022izyysjlem75m1k6qtpol";
        [self.requestSerializer setValue:[NSString stringWithFormat:@"JSESSIONID=%@",UserUtils.shared.session] forHTTPHeaderField:@"Cookie"];
    }
    
    NSLog(@"\n【url: %@】\n【body:\n %@】",urlStr,parameters);
    
//    NSString *bodyStr = [para yy_modelToJSONString];
//    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request;
    if ([method isEqualToString:GET]) {
        request = [self.requestSerializer requestWithMethod:@"GET" URLString:url parameters:parameters error:nil];
        request.timeoutInterval= 30;
//        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        
    }
    else {
        request = [self.requestSerializer requestWithMethod:@"POST" URLString:url parameters:parameters error:nil];
        request.timeoutInterval= 30;
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//        [request setHTTPBody:bodyData];
    }
    [[self dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"uploadProgress %f", uploadProgress.completedUnitCount * 1.0 / uploadProgress.totalUnitCount);
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"downloadProgress %f", downloadProgress.completedUnitCount * 1.0 / downloadProgress.totalUnitCount);
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"\n【 url：%@ 】\n【 responseObj：\n%@ 】",response.URL.absoluteString,responseDictionary);
            success(response,responseDictionary);
            [self dealLoginOut:responseDictionary];
        }
        else {
            failure(response,error);
        }
    }] resume];
}

- (void)getUrlStr:(NSString *)urlStr
       parameters:(id)parameters
          success:(void (^)(NSURLResponse * _Nonnull response, id _Nullable responseObj, NSDictionary * _Nullable otherResponse))success
          failure:(void (^)(NSURLResponse * _Nullable response, NSError * _Nonnull error))failure
{
    [self requestUrlStr:urlStr method:GET parameters:parameters success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj) {
        if (responseObj && [responseObj isKindOfClass:[NSDictionary class]]) {
            NSDictionary *responseDictionary = responseObj;
            if ([responseDictionary.allKeys containsObject:@"msg"]) {
                success(response,nil,responseDictionary);
                [MBProgressHUD showError:responseDictionary[@"msg"]];
            }
            else {
                success(response, responseDictionary, nil);
            }
        }
        else {
            success(response, nil, nil);
            [MBProgressHUD showError:@"Json格式错误，解析异常"];
        }
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        failure(response, error);
        [MBProgressHUD showError:error.userInfo[NSLocalizedDescriptionKey]];
    }];
}

- (void)getUrlStr:(NSString *)urlStr
       parameters:(id)parameters
      entityClass:(Class)entityClass
          success:(void (^)(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse))success
          failure:(void (^)(NSURLResponse * _Nullable response, NSError * _Nonnull error))failure
{
    [self requestUrlStr:urlStr method:GET parameters:parameters success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj) {
        if (responseObj && [responseObj isKindOfClass:[NSDictionary class]]) {
            NSDictionary *responseDictionary = responseObj;
            if ([responseDictionary.allKeys containsObject:@"msg"]) {
                success(response,nil,responseDictionary);
                [MBProgressHUD showError:responseDictionary[@"msg"]];
            }
            else {
                BaseEntity *baseEntity = [BaseEntity entity:entityClass fromDictionary:responseObj];
                success(response, baseEntity, nil);
                if (baseEntity.code.intValue != 200) {
                    [MBProgressHUD showError:baseEntity.message];
                }
            }
        }
        else {
            success(response, nil, nil);
            [MBProgressHUD showError:@"Json格式错误，解析异常"];
        }
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        failure(response, error);
        [MBProgressHUD showError:error.userInfo[NSLocalizedDescriptionKey]];
    }];
}

- (void)postUrlStr:(NSString *)urlStr
        parameters:(id)parameters
           success:(void (^)(NSURLResponse * _Nonnull response, id _Nullable responseObj, NSDictionary * _Nullable otherResponse))success
           failure:(void (^)(NSURLResponse * _Nullable response, NSError * _Nonnull error))failure
{
    [self requestUrlStr:urlStr method:POST parameters:parameters success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj) {
        if (responseObj && [responseObj isKindOfClass:[NSDictionary class]]) {
            NSDictionary *responseDictionary = responseObj;
            if ([responseDictionary.allKeys containsObject:@"msg"]) {
                success(response,nil,responseDictionary);
                [MBProgressHUD showError:responseDictionary[@"msg"]];
            }
            else {
                success(response, responseDictionary, nil);
            }
        }
        else {
            success(response, nil, nil);
            [MBProgressHUD showError:@"Json格式错误，解析异常"];
        }
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        failure(response, error);
        [MBProgressHUD showError:error.userInfo[NSLocalizedDescriptionKey]];
    }];
}

- (void)postUrlStr:(NSString *)urlStr
        parameters:(nullable id)parameters
       entityClass:(Class)entityClass
           success:(void (^)(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse))success
           failure:(void (^)(NSURLResponse * _Nullable response, NSError * _Nonnull error))failure
{
    [self requestUrlStr:urlStr method:POST parameters:parameters success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj) {
        
        if (responseObj && [responseObj isKindOfClass:[NSDictionary class]]) {
            NSDictionary *responseDictionary = responseObj;
            if ([responseDictionary.allKeys containsObject:@"msg"]) {
                success(response,nil,responseDictionary);
                [MBProgressHUD showError:responseDictionary[@"msg"]];
            }
            else {
                BaseEntity *baseEntity = [BaseEntity entity:entityClass fromDictionary:responseObj];
                success(response, baseEntity, nil);
                if (baseEntity.code.intValue != 200) {
                    [MBProgressHUD showError:baseEntity.message];
                }
            }
        }
        else {
            success(response, nil, nil);
            [MBProgressHUD showError:@"Json格式错误，解析异常"];
        }
        
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        failure(response, error);
        [MBProgressHUD showError:error.userInfo[NSLocalizedDescriptionKey]];
    }];
}


- (void)uploadUrlStr:(NSString *)urlStr
              images:(NSArray *)images
          parameters:(nullable id)parameters
        fileDataName:(NSString *)fileDataName
             success:(void (^)(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObj))success
             failure:(void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure
{
    self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                            @"text/html",
                                                                            @"image/jpeg",
                                                                            @"image/png",
                                                                            @"application/octet-stream",
                                                                            @"text/json",
                                                                            nil];

    NSString *url = [NSString stringWithFormat:@"%@%@", SERVERADDRS, urlStr];
//    NSMutableDictionary *para = parameters;
//    if (para) {
//        para = para.mutableCopy;
//    }
//    else {
//        para = @{}.mutableCopy;
//    }
    if ([UserUtils shared].session.length > 0) {
        [self.requestSerializer setValue:[NSString stringWithFormat:@"JSESSIONID=%@",UserUtils.shared.session] forHTTPHeaderField:@"Cookie"];
    }
    NSLog(@"\n【url: %@】\n【body:\n %@】",url,parameters);
    [self POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i = 0; i < images.count; i++) {
            
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            NSString *fileName = [NSString stringWithFormat:@"%@#%d.png",[dateFormatter stringFromDate:[NSDate date]],i];
            NSData *imgData = UIImageJPEGRepresentation(images[i], 1);
            [formData appendPartWithFileData:imgData name:fileDataName fileName:fileName mimeType:@"image/png"];
        }
//        [formData appendPartWithFileData:imgData name:@"file" fileName:@"abc.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",responseDictionary);
        if (responseDictionary && [responseDictionary isKindOfClass:[NSDictionary class]]) {
            
            
            success(task, responseDictionary);
                
            
            
        }
        else {
            success(task,nil);
            [MBProgressHUD showError:@"Json格式错误，解析异常"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(task,error);
        [MBProgressHUD showError:error.userInfo[NSLocalizedDescriptionKey]];
    }];
}


- (void)dealLoginOut:(NSDictionary *)responseObject
{
    NSString *code = responseObject[@"code"];
    if (code.intValue == 901) {
        [UserUtils.shared clearData];
        [ANAlertManager alertSimpleMessage:@"登录失效，请重新登录" handlerTitle:@"重新登录" handler:^(UIAlertAction * _Nonnull action) {
            [UserUtils showLoginVc];
        }];
//        [UIApplication sharedApplication].keyWindow.rootViewController = [[ANNavigationController alloc] initWithRootViewController:[[ANLoginController alloc] init]];
    }
}

@end
